package com.example.demo.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.util.CyUtils;
import com.example.demo.bean.Cyjl;
import com.example.demo.config.MessageConfig;
import com.example.demo.config.StatusType;
import com.example.demo.mapper.CyMapper;
import com.example.demo.message.Message;
import com.example.demo.request.WxRequest;
import com.example.demo.service.TextService;
import com.example.demo.util.CacheUtil;
import com.example.demo.util.SSWDUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
public class TextServiceImpl implements TextService {

    @Resource
    private CyMapper cyMapper;

    @Override
    public Message getTextMessage(WxRequest wxRequest) {

        /**
         *       message = "<xml>\n" +
         *                     "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
         *                     "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
         *                     "  <CreateTime>"+new Date().getTime()/1000+"</CreateTime>\n" +
         *                     "  <MsgType><![CDATA[text]]></MsgType>\n" +
         *                     "  <Content><![CDATA["+content+"]]></Content>\n" +
         *                     "</xml>";
         * @param wxRequest
         * @return
         */
        Message message = new Message(wxRequest);//获取消息的基本信息
        //根据不同业务进行不同的处理 查看是否有关键词 且 关键词为 null
        String toUserName = message.getToUserName();
        System.out.println("toUserName:"+toUserName);

        String status = CacheUtil.get(toUserName); // 获取当前用户的状态

        String content = wxRequest.getContent();
        if("exit".equals(content)){
            //清空所有状态
            message.setContent(MessageConfig.EXIT_MESSAGE);
            CacheUtil.set(toUserName,StatusType.CYJL,1);
            CacheUtil.set(toUserName,StatusType.CSZ,1);
            CacheUtil.set(toUserName,StatusType.SSWD,1);
            return message;
        }

        //成语接龙状态处理
        if(StatusType.CYJL.equals(status)){
            String oldCy = CacheUtil.get(toUserName + "_cy");
            String newCy = message.getContent();
            List<String> lastPingYin = CyUtils.getLastPingYin(oldCy);
            List<String> firstPingYin = CyUtils.getFirstPingYin(newCy);
            boolean b = lastPingYin.removeAll(firstPingYin);
            if(b&&(isCy(newCy)||CyUtils.selectCYByNet(newCy))){
                //接龙成功

                //查询一个成语
                List<Cyjl> cyjls = new ArrayList<>();
                List<String> lastPingYinList = CyUtils.getLastPingYin(newCy);
                for (String lastPingYin1 : lastPingYinList) {
                    QueryWrapper<Cyjl> cyjlQueryWrapper = new QueryWrapper<>();
                    cyjlQueryWrapper.likeRight("spell",lastPingYin1+" ");
                    cyjls.addAll(cyMapper.selectList(cyjlQueryWrapper));
                }
                //查询获取所有符合的成语,随机返回一个
                if(cyjls.size()<=0){
                    message.setContent(MessageConfig.CYJL_SUCCESS_MESSAGE);
                    CacheUtil.set(toUserName,StatusType.NULL,1);
                    CacheUtil.set(toUserName+"_cy",null,1);
                }else {
                    String name = cyjls.get(RandomUtil.randomInt(cyjls.size())).getName();
                    List<String> lastPingYin1 = CyUtils.getLastPingYin(name);
                    CacheUtil.set(toUserName+"_cy",name);
                    message.setContent(name+lastPingYin1+MessageConfig.CYJL_TS_MESSAGE);
                }



            }else {
                //接龙失败 查询可以接龙的成语
                List<Cyjl> cyjls = new ArrayList<>();
                List<String> lastPingYinList = CyUtils.getLastPingYin(oldCy);
                for (String lastPingYin1 : lastPingYinList) {
                    QueryWrapper<Cyjl> cyjlQueryWrapper = new QueryWrapper<>();
                    cyjlQueryWrapper.likeRight("spell",lastPingYin1+" ");
                    cyjls.addAll(cyMapper.selectList(cyjlQueryWrapper));
                }

                String reMessage = MessageConfig.CYJL_ERROR_MESSAGE1+oldCy+MessageConfig.CYJL_ERROR_MESSAGE2+newCy+MessageConfig.CYJL_ERROR_MESSAGE3;
                for (int i = 0; i < 15; i++) {
                    reMessage += cyjls.get(i).getName()+"\n";
                }
                reMessage += MessageConfig.CYJL_ERROR_MESSAGE4;
                message.setContent(reMessage);
                CacheUtil.set(toUserName,StatusType.NULL,1);
                CacheUtil.set(toUserName+"_cy",null,1);
            }

        }

        //猜数字状态处理
        if(StatusType.CSZ.equals(status)){
            //获取当前用户的猜数字
            String save = CacheUtil.get(toUserName + "_csz");
            if(save==null){
                message.setContent(MessageConfig.CSZ_ERROR_MESSAGE);
            }else {
                int csz = Integer.parseInt(save);
                int i = Integer.parseInt(content);
                if(csz==i){
                    message.setContent(MessageConfig.CSZ_SUCCESS_MESSAGE);
                    CacheUtil.set(toUserName,StatusType.NULL,1);
                    CacheUtil.set(toUserName+"_csz",null,1);
                }else if(csz>i){
                    message.setContent(MessageConfig.CSZ_ERROR_MESSAGE1);
                }else {
                    message.setContent(MessageConfig.CSZ_ERROR_MESSAGE2);
                }
            }
        }

        //谁是卧底
        if(StatusType.SSWD.equals(status)){

            //设置用户在游戏中的状态 0 表示刚刚进入, 1 表示进入房间  2 表示已经准备 3 人齐开始游戏
            String sta = CacheUtil.get(toUserName + "_sswd");

            //刷新返回当前用户的状态和消息
            if("s".equals(content)){
                //刷新
                message.setContent(SSWDUtil.getMessage(toUserName));
            }

            //操作游戏主页
            if("游戏主页".equals(sta)){
                //获取用户输入的 1 或者 2 1为创建房间 返回房间号 2为加入房间
                if("1".equals(content)){
                    //创建房间
                    String msg = SSWDUtil.createRoom(toUserName);
                    message.setContent(msg);
                    CacheUtil.set(toUserName+"_sswd","房间页未准备");
                }
                if("2".equals(content)){
                    //加入房间
                    message.setContent("请输入房间号:");
                    CacheUtil.set(toUserName+"_sswd","等待输入房间号");
                }
            }

            if("等待输入房间号".equals(sta)){
                //加入房间
                try{
                    String msg = SSWDUtil.joinRoom(toUserName, content);
                    message.setContent(msg);
                    CacheUtil.set(toUserName+"_sswd","房间页未准备");
                }catch (Exception e) {
                    message.setContent("加入房间失败,房间号:" + content);
                    CacheUtil.set(toUserName + "_sswd", "游戏主页");
                }

            }

            if("房间页未准备".equals(sta)){
                if("1".equals(content)){
                    //加入房间
                    try{
                        String msg = SSWDUtil.ready(toUserName);
                        message.setContent(msg);
                        CacheUtil.set(toUserName+"_sswd","房间页已准备");
                    }catch (Exception e) {
                        message.setContent("准备失败,请重试");
                    }
                }

//                if("s".equals(content)){
//                    //刷新
//                    String msg = SSWDUtil.refresh(toUserName);
//                    message.setContent(msg);
//                }

            }
            if("房间页已准备".equals(sta)){
                if("1".equals(content)){
                    //取消准备
                    boolean b = SSWDUtil.cancelReady(toUserName);
                    if(b){
                        message.setContent("取消准备成功");
                        CacheUtil.set(toUserName+"_sswd","房间页未准备");
                    }else {
                        message.setContent("取消准备失败,请重试");
                    }
                }

                if("2".equals(content)){
                    //房主确认开始游戏
                    try{
                        String msg = SSWDUtil.startGame(toUserName);
                        message.setContent(msg);
                        CacheUtil.set(toUserName+"_sswd","游戏开始");
                    }catch (Exception e) {
                        message.setContent("游戏开始失败,请重试");
                    }

                }
//                if("s".equals(content)){
//                    //刷新
//                    String msg = SSWDUtil.refresh(toUserName);
//                    message.setContent(msg);
//                }
            }

            if("游戏开始".equals(sta)){

            }

            if("等待回复描述词".equals(sta)){
//                if("s".equals(content)){
//                    //刷新
//                    String msg = SSWDUtil.refresh(toUserName);
//                    message.setContent(msg);
//                }
                //把描述词存入缓存
                SSWDUtil.setDescribe(toUserName,content);
                CacheUtil.set(toUserName+"_sswd","等待投票");
                message.setContent("描述词已经设置,按s刷新等待其他用户设置描述词");
            }
            if("等待投票".equals(sta)){
//                if("s".equals(content)){
//                    //显示描述词
//                    String msg = SSWDUtil.refreshDescribe(toUserName);
//                    message.setContent(msg);
//                }

            }
        }

        //无状态处理
        if(StatusType.NULL.equals(status)){
            message.setContent(MessageConfig.NOT_FOUND_MESSAGE);
            //发起成语接龙
            if(StatusType.CYJL.equals(wxRequest.getContent())){
                //调整改用户状态为 成语接龙状态
                CacheUtil.set(toUserName,StatusType.CYJL);
                //随机获取一个成语
                String cy = cyMapper.selectRandOne(RandomUtil.randomInt(30000));
                CacheUtil.set(toUserName+"_cy",cy);
//                content = "我给出的成语是:<"+content+"> 您需要给出拼音是:"+cyUtils.getLastPingYin(content)+" 开头的成语来继续接龙!";
                List<String> lastPingYin = CyUtils.getLastPingYin(cy);
                message.setContent(cy+lastPingYin+"请回复成语接龙来继续接龙!");
            }

            //发起猜数字
            if(StatusType.CSZ.equals(wxRequest.getContent())){
                //调整改用户状态为 成语接龙状态
                CacheUtil.set(toUserName,StatusType.CSZ);
                //生成一个随机数字
                int i = RandomUtil.randomInt(100);
                System.out.println(i);
                CacheUtil.set(toUserName+"_csz",i+"");
                message.setContent("我给出了一个0-99,请回复数字来猜测!");
            }

            //发起谁是卧底
            if(StatusType.SSWD.equals(wxRequest.getContent())){
                String start = SSWDUtil.start(toUserName);
                CacheUtil.set(toUserName+"_sswd","游戏主页");
                message.setContent(start);
            }

        }
        return message;
    }

    private boolean isCy(String newCy) {
        List<String> stringList = cyMapper.selectByTop(newCy);
        return stringList.size()>0;
    }
}
